package com.visionet.school.app.web.common.security.shiro;

import com.visionet.school.app.web.common.security.shiro.entity.ShiroToken;
import com.visionet.school.app.web.entity.user.User;
import com.visionet.school.app.web.entity.enums.UserStatus;
import com.visionet.school.app.web.service.user.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created by hxpeng on 2017/3/9.
 */

/**
 * 通用/基础 授权认证
 */
public class CurrencyRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }


    /**
     * 登录验证
     * @param authenticationToken
     * @return
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        ShiroToken token = (ShiroToken) authenticationToken;
        User user = userService.login(token.getUsername(),token.getPswd());
        if(null == user){
            throw new AccountException("帐号或密码不正确！");
        }else if(UserStatus.LOCKED.toKey().equals(user.getStatus())){
            throw new DisabledAccountException("帐号登陆次数超过限制，已被锁定！");
        }else if(UserStatus.INVALID.toKey().equals(user.getStatus())){
            throw new DisabledAccountException("无效账号！");
        }else{
            user.setLastLoginTime(new Date());
            userService.save(user);
        }
        return new SimpleAuthenticationInfo(user,user.getPassword(), getName());
    }

    /**
     * 清空当前用户权限信息
     */
    public  void clearCachedAuthorizationInfo() {
        PrincipalCollection principalCollection = SecurityUtils.getSubject().getPrincipals();
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principalCollection, getName());
        super.clearCachedAuthorizationInfo(principals);
    }
    /**
     * 指定principalCollection 清除
     */
    public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principalCollection, getName());
        super.clearCachedAuthorizationInfo(principals);
    }
}
